﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using CardInChina.Data.Entity;
using System.Security.Cryptography;

namespace CardInChina.Security
{
    public class CardMembershipProvider : MembershipProvider
    {
        public override string ApplicationName
        {
            get;
            set;
        }

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            if (String.IsNullOrWhiteSpace(username)
                || String.IsNullOrWhiteSpace(oldPassword)
                || String.IsNullOrWhiteSpace(newPassword))
                throw new ApplicationException("用户名，密码，新密码不能为空");

            var hashedPwd = MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(oldPassword));

            using (var dc = new CardEntities())
            {
                var user = dc.customers.FirstOrDefault(p => p.username == username && p.password == hashedPwd);
                if (user == null)
                    throw new ApplicationException("用户名或密码不正确");

                user.password = MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(newPassword));
                dc.SaveChanges();
            }

            return true;
        }

        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
        {
            if (String.IsNullOrWhiteSpace(username)
             || String.IsNullOrWhiteSpace(password)
             || String.IsNullOrWhiteSpace(email))
                throw new ApplicationException("用户名，密码，电子邮件地址不能为空");

            using (var dc = new CardEntities())
            {
                var user = dc.customers.FirstOrDefault(p => p.username == username);
                if (user == null)
                {
                    status = MembershipCreateStatus.DuplicateUserName;
                    return null;
                }

                user = dc.customers.FirstOrDefault(p => p.email == email);
                if (user == null)
                {
                    status = MembershipCreateStatus.DuplicateEmail;
                    return null;
                }

                var customer = new customer
                {
                    username = username,
                    password = MD5.Create().ComputeHash(Encoding.ASCII.GetBytes(password)),
                    email = email,
                    reg_time = DateTime.Now,
                };
                dc.customers.AddObject(customer);

                try
                {
                    dc.SaveChanges();
                    status = MembershipCreateStatus.Success;
                    return new MembershipUser(
                        this.GetType().Name,
                        customer.name,
                        null,
                        customer.email,
                        null,
                        null,
                        false,
                        false,
                        customer.reg_time,
                        customer.lastlogin_time,
                        customer.lastlogin_time,
                        customer.lastlogin_time,
                        customer.lastlogin_time
                        );
                }
                catch (Exception e)
                {
                    //TODO: Log error!
                    status = MembershipCreateStatus.ProviderError;
                    return null;
                }
            }
        }

        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            throw new NotImplementedException();
        }

        public override bool EnablePasswordReset
        {
            get { throw new NotImplementedException(); }
        }

        public override bool EnablePasswordRetrieval
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException();
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException();
        }

        public override string GetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(string username, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            throw new NotImplementedException();
        }

        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException();
        }

        public override int MaxInvalidPasswordAttempts
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredNonAlphanumericCharacters
        {
            get { throw new NotImplementedException(); }
        }

        public override int MinRequiredPasswordLength
        {
            get { throw new NotImplementedException(); }
        }

        public override int PasswordAttemptWindow
        {
            get { throw new NotImplementedException(); }
        }

        public override MembershipPasswordFormat PasswordFormat
        {
            get { throw new NotImplementedException(); }
        }

        public override string PasswordStrengthRegularExpression
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresQuestionAndAnswer
        {
            get { throw new NotImplementedException(); }
        }

        public override bool RequiresUniqueEmail
        {
            get { throw new NotImplementedException(); }
        }

        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException();
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException();
        }

        public override bool ValidateUser(string username, string password)
        {
            throw new NotImplementedException();
        }
    }
}
